import datetime
import math

from django import http
from django.contrib.gis.geos import MultiPolygon, Point, Polygon
from django.core.urlresolvers import reverse

from connie2_django.connie2 import models


def connie_for_beach(request, lon, lat):
    lon, lat = float(lon), float(lat)
    # get hard-coded model bounds, and check we're operating within
    # them:
    fields = models.VelocityFields.objects.get(key='STORM')
    if not fields.bounds.contains(Point((lon, lat))):
        return http.HttpResponseNotFound()

    # otherwise, get the specified grid cell (by rounding down and up
    # to the increments):
    lonInc, latInc = fields.cellWidth, fields.cellHeight
    x0 = math.floor(lon / lonInc) * lonInc
    x1 = math.ceil(lon / lonInc) * lonInc
    y0 = math.floor(lat / latInc) * latInc
    y1 = math.ceil(lat / latInc) * latInc

    # create a run, based on that point and 27/March/2012, which is
    # what the marvlis portal is currently hardcoded to:
    run = models.ConnieRun()
    # We want to check the /sources/ of water at a point:
    run.isSource = False
    run.velocityFields = fields
    run.regions = MultiPolygon([Polygon.from_bbox((x0, y0, x1, y1))])
    run.boundingBox = run.calcBounds()

    day = datetime.date(1900, 3, 27)
    run.spawningFromDate = day
    run.spawningToDate = day

    # Now, see if we already have a similar request, and if so just
    # use that one rather than creating a fresh one (ie, caching).
    # Note, in this particular case we actually only need to bother
    # about the boundingBox, but I've already written a custom manager
    # so let's use that.
    similar_runs = models.ConnieRun.objects.similar_to(run)
    if similar_runs:
        run = similar_runs[0]
    else:
        run.save()

        run.years.add(models.YearForAveraging.objects.get(year=2012))

        phase = models.LarvalPhase()
        phase.connieRun = run
        phase.phaseLongevity = 5    # Default
        phase.save()

        level = models.LarvalPhaseLevel()
        level.verticalLevel = fields.depths.order_by('depth')[0]
        level.larvalPhase = phase
        level.save()

    # Get the id, and kick it off from the homepage:
    return http.HttpResponseRedirect(reverse('frontpage') + '#' + str(run.pk))
